package com.kenyi.co.wxapi;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.kenyi.co.common.bean.WXBaseRespEntity;
import com.kenyi.co.okhttp.OkHttpUtils;
import com.kenyi.co.okhttp.callback.StringCallback;
import com.kenyi.co.ui.login.Bean.AuthLoginBean;
import com.kenyi.co.ui.login.LoginPhoneActivity;
import com.kenyi.co.ui.login.RegisterActivity;
import com.kenyi.co.ui.me.ui.SettingActivity;
import com.kenyi.co.utils.Config;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.NetConfig;
import com.kenyi.co.utils.SharepUtils;
import com.kenyi.co.utils.ToastUtil;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.kenyi.co.utils.CommonUtils.getAppVersion;

/**
 * description ：
 * project name：CCloud
 * author : Vincent
 * creation date: 2017/6/9 18:13
 *
 * @version 1.0
 */

public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    /**
     * 微信登录相关
     */
    private IWXAPI api;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //通过WXAPIFactory工厂获取IWXApI的示例
        api = WXAPIFactory.createWXAPI(this, Config.APP_ID_WX, true);
        //将应用的appid注册到微信
        api.registerApp(Config.APP_ID_WX);

        //注意：
        //第三方开发者如果使用透明界面来实现WXEntryActivity，需要判断handleIntent的返回值，如果返回值为false，则说明入参不合法未被SDK处理，应finish当前透明界面，避免外部通过传递非法参数的Intent导致停留在透明界面，引起用户的疑惑
        try {
            boolean result = api.handleIntent(getIntent(), this);
            if (!result) {

                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        api.handleIntent(data, this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        WXBaseRespEntity entity = JSON.parseObject(JSON.toJSONString(baseResp), WXBaseRespEntity.class);


        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                getUserInfo(entity.getCode());
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                finish();
                break;
            case BaseResp.ErrCode.ERR_BAN:
                break;
            default:

                finish();
                break;
        }
    }


    private void getUserInfo(String access_token) {
        String deviceId = "";
        if (Build.VERSION.SDK_INT >= 23) {
            if (WXEntryActivity.this.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) ==
                    PackageManager.PERMISSION_GRANTED) {
                TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
                deviceId = tm.getDeviceId();
            }
        } else {
            TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            deviceId = tm.getDeviceId();
        }
        Map<String, String> params = new HashMap<>();

        params.put("deviceId", deviceId);
        params.put("code", access_token);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        String url = NetConfig.AUTH_WXLOGIN;
        OkHttpUtils.post()
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {


                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        int num = 0;
                        AuthLoginBean packlist = gson.fromJson(response, AuthLoginBean.class);
                        int code = packlist.getCode();
                        if (code == 200) {
                            AuthLoginBean.DatasBean mUserInfo;
                            mUserInfo = packlist.getDatas();
                            SharepUtils.saveUserInfo(WXEntryActivity.this, mUserInfo);
                            ToastUtil.showShort(getApplicationContext(), packlist.getMsg());

                            List<String> LikeTags1;
                            try {
                                LikeTags1 = SharepUtils.getShDataList(WXEntryActivity.this, SharepUtils.USER_FAV_TAGS_LIST, String.class);
                                SharepUtils.setShDataList(WXEntryActivity.this, SharepUtils.USER_FAV_TAGS_lOCAL, LikeTags1);
                                List<String> tags = new ArrayList<String>();
                                tags = packlist.getDatas().getUserInfo().getLikeTags();
                                if (tags!=null&&tags.size() > 0) {
                                    List<String> LikeTags = packlist.getDatas().getUserInfo().getLikeTags();
                                    SharepUtils.setShDataList(WXEntryActivity.this, SharepUtils.USER_FAV_TAGS_LIST, LikeTags);

                                }
                            } catch (Exception e) {

                            }

                            Intent intent = getIntent();
                            SharepUtils.setString_info(WXEntryActivity.this,"1", SharepUtils.USER_IS_LOGIN);
                            intent.putExtra("is_ok","1");
                            WXEntryActivity.this.setResult(0,intent);
                            finish();

                        }
                    }
                });
    }

}
